import urllib.request
import json
import os

servers = [
    "https://api.asmr-100.com/",
    "https://api.asmr-200.com/",
    "https://api.asmr-300.com/",
    "https://api.asmr.one/",
]


def __fetch(path):
    req = urllib.request.Request('https://api.asmr-300.com/' + path)
    req.add_header('Referer', 'https://www.asmr.one')
    req.add_header('User-Agent',
                   'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 '
                   'Safari/537.36 Edg/115.0.1901.188')
    try:
        r = urllib.request.urlopen(req)
        data = r.read().decode("utf-8")
        r.close()
        return data
    except urllib.error.HTTPError as e:
        print("请求异常\n", e)
        raise


def get_rj(s):
    s = str(s).lower().strip()
    if s.startswith("rj"):
        s = s[2:]
    if s.isnumeric():
        return s


def get_work(rj):
    data = __fetch("api/workInfo/" + str(rj))
    return json.loads(data)


def get_tracks(rj):
    data = __fetch("api/tracks/" + str(rj))
    return json.loads(data)


def download(track, dir="."):
    if not os.path.exists(dir):
        os.makedirs(dir)
    if track["type"] == "folder":
        for t in track["children"]:
            download(t, dir + "/" + track["title"])
    else:
        _download(dir + "/" + track["title"], track["mediaDownloadUrl"])


def _filter(path):
    """
    过滤文件类型
    """
    if str(path).lower().endswith(".wav"):
        return False
    return True


def _download(name, url):
    if _filter(url):
        urllib.request.urlretrieve(url, name)
